const http = require('http');
// 引入基于Promise的FS模块
const fs = require('fs').promises;
const path = require('path');
const queryString = require('queryString');
const url = require('url');
const mime = require('mime')
// 将createStream结构出来
let createStream = require('fs');
// 将同步解析改为Promise的

class server{
    async handleServer(request,response) {
        // 注意这里的this并不是这个实例，这里的this指向的其实是http实例，
        // 所以这个函数在调用的时候要使用bind来绑定外界的this,bind之后就是外界的this
        console.log(this);
        const {pathname} = url.parse(request.url);
        const absPath = path.join(__dirname, pathname);
        try {
            let statObj = await fs.stat(absPath);
            if(statObj.isDirectory()){
                absPath = path.join(absPath, 'index.html');
            }
            this.sendFile(request,response,absPath);
        } catch (e) {
            this.sendError(request,response);
        }
    }
    /**
     * 开启服务器
     */
    start(){
        let server = http.createServer(this.handleServer.bind(this));
        server.listen(...arguments);
    }

    /**
     * 返回文件未找到
     * @param {req}} request 
     * @param {res} response 
     */
    sendError(request,response){
        response.statusCode = 404;
        response.end(' Not Found');
    }
    sendFile(req,res,absPath){
        const fileType = mime.getType(absPath);
        res.setHeader('Context-Type',fileType + ';charset=utf-8');
        // 用可读流，将文件流写给RES，就不用自己去readFile了
        createStream(absPath).pipe(res);
    }
}



let server = new Server();
server.start(3000);